//
//  STTabView.swift
//  iPhone
//
//  Created by Toj on 11/17/23.
//

import Foundation

protocol STTabViewDelegate: NSObjectProtocol {
    
    func tabView(_ tabView: STTabView, didSelected tab: STTabViewModel)
}

class STTabView: UIView {
    
    weak var delegate: STTabViewDelegate?
    
    var tabs: [STTabViewModel] = [] { didSet {
        collectionView.reloadData()
    } }
    
    public var selectedIndex = -1 { willSet {
        let count = tabs.count
        guard count > newValue, newValue >= 0 else { return }
        guard selectedIndex != newValue else { return }
        
        if count > selectedIndex, selectedIndex >= 0 {
            let tab = tabs[selectedIndex]
            tab.isSelected = false
        }
        
        let tab = tabs[newValue]
        tab.isSelected = true
        
        delegate?.tabView(self, didSelected: tab)
        collectionView.scrollToItem(at: IndexPath(row: newValue, section: 0), at: .centeredHorizontally, animated: true)
    } }
    
    var tab: STTabViewModel? {
        let count = tabs.count
        guard selectedIndex < count else { return nil }
        return tabs[selectedIndex]
    }
    
    var title: String {
        return tab?.title ?? ""
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
        setupMakeInitialize()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /** <#NOTE#> **/
    private lazy var backgrounImageView: UIImageView = {
        let view = UIImageView()
        view.image = "player_tabs_background_img".to_image
        return view
    }()
    
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        // cell之间 垂直间距
        layout.minimumLineSpacing = 0
        // cell之间 水平间距
        layout.minimumInteritemSpacing = 18
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .clear
        view.contentInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        view.scrollsToTop = false
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.register(cellClass: STTabViewCell.self)
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    var lineViewHeight: CGFloat = 4 { didSet {
        lineView.st_cornerRadius = lineViewHeight * 0.5
    } }
    
    var lineViewBackgroundColor: UIColor? { didSet {
        lineView.backgroundColor = lineViewBackgroundColor
    } }
    private(set) lazy var lineView = UIView()
    
    private var selectedIndexPath: IndexPath? { didSet {
        guard let indexPath = selectedIndexPath else { return }
        selectedIndex = indexPath.row
        collectionView.reloadData()
    } }
    
    private var tabCell: STTabViewCell? { willSet {
        guard let cell = newValue else { return }
        var center = lineView.center
        center.x = cell.center.x
        UIView.animate(withDuration: 0.2) {
            self.lineView.center = center
        }
    } }
}

// MARK: - Public
extension STTabView {
    
    func reloadTabs() {
        collectionView.reloadData()
    }
}

extension STTabView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tabs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifierClass: STTabViewCell.self, for: indexPath)
        cell.tab = tabs[indexPath.row]
     
        if selectedIndexPath == nil && indexPath.row == selectedIndex {
            selectedIndexPath = indexPath
        }
        return cell
    }
}

extension STTabView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard indexPath == selectedIndexPath else { return }
        guard let cell = cell as? STTabViewCell else { return }
        tabCell = cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if selectedIndexPath?.row == indexPath.row { return }
        selectedIndexPath = indexPath
    }
}

extension STTabView: UICollectionViewDelegateFlowLayout {
    
    // cell 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let tab = tabs[indexPath.row]
        return tab.contentSize
    }
}

extension STTabView {
    
    private func setupMakeAddSubviews() {
        
        addSubview(backgrounImageView)
        addSubview(collectionView)
        collectionView.addSubview(lineView)
        collectionView.bringSubviewToFront(lineView)
    }
    
    private func setupMakeLayoutSubviews() {
        guard frame != .zero else { return }
        
        backgrounImageView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        var lineFrame: CGRect = .zero
        lineFrame.size.width = 52
        lineFrame.size.height = lineViewHeight
        lineFrame.origin.x = 0
        lineFrame.origin.y = frame.height - lineFrame.size.height
        lineView.frame = lineFrame
    }
    
    private func setupMakeInitialize() {
        lineViewBackgroundColor = "#00BCF7".to_color
    }
}
